<template>
	<div class="page">
		<div class="page-header">
			<h1 class="page-title">社会服务</h1>
			<p class="page-subtitle">在线填报/更新社会服务信息，上传证明材料</p>
		</div>

		<div style="margin-bottom: 20px;">
			<el-button type="success" @click="exportData">
				<el-icon><Download /></el-icon>
				导出数据
			</el-button>
			<el-button type="primary" style="margin-left: 8px;" @click="openCreate()">
				<el-icon><Plus /></el-icon>
				在线填报
			</el-button>
		</div>

		<el-card>
			<el-table :data="tableData" style="width: 100%">
				<el-table-column prop="serviceType" label="类型" width="160" />
				<el-table-column prop="title" label="标题/角色" min-width="200" show-overflow-tooltip />
				<el-table-column prop="organizationName" label="邀请/委托单位" min-width="200" show-overflow-tooltip />
				<el-table-column prop="level" label="级别" width="100">
					<template #default="{ row }">
						<el-tag :type="levelTag(row.level)">{{ row.level || '-' }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="startDate" label="开始" width="120" />
				<el-table-column prop="endDate" label="结束" width="120" />
				<el-table-column prop="status" label="状态" width="110">
					<template #default="{ row }">
						<el-tag :type="statusTag(row.status)">{{ statusText(row.status) }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="220" fixed="right">
					<template #default="{ row }">
						<el-button size="small" @click="handleView(row)">查看</el-button>
						<el-button size="small" type="primary" :disabled="!canEdit(row)" @click="handleEdit(row)">编辑</el-button>
						<el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>

		<el-dialog v-model="showDialog" :title="isEdit ? '编辑社会服务' : '新增社会服务'" width="720px">
			<el-form ref="formRef" :model="form" :rules="rules" label-width="110px">
				<el-row :gutter="16">
					<el-col :span="12">
						<el-form-item label="类型" prop="service_type">
							<el-select v-model="form.service_type" placeholder="请选择" style="width: 100%" filterable>
								<el-option label="政府顾问" value="政府顾问" />
								<el-option label="企业咨询专家" value="企业咨询专家" />
								<el-option label="评审专家" value="评审专家" />
								<el-option label="公共政策" value="公共政策" />
								<el-option label="调研报告" value="调研报告" />
								<el-option label="公益活动" value="公益活动" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="级别" prop="level">
							<el-select v-model="form.level" placeholder="请选择" style="width: 100%">
								<el-option label="校级" value="校级" />
								<el-option label="市级" value="市级" />
								<el-option label="省级" value="省级" />
								<el-option label="国家级" value="国家级" />
								<el-option label="国际级" value="国际级" />
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>

				<el-form-item label="标题/角色" prop="title">
					<el-input v-model="form.title" placeholder="如：数字政府建设顾问/评审专家" />
				</el-form-item>
				<el-form-item label="单位" prop="organization_name">
					<el-input v-model="form.organization_name" placeholder="邀请/委托单位" />
				</el-form-item>

				<el-row :gutter="16">
					<el-col :span="12">
						<el-form-item label="开始日期" prop="start_date">
							<el-date-picker v-model="form.start_date" type="date" value-format="YYYY-MM-DD" style="width:100%" :disabled-date="disableStart" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="结束日期" prop="end_date">
							<el-date-picker v-model="form.end_date" type="date" value-format="YYYY-MM-DD" style="width:100%" :disabled-date="disableEnd" />
						</el-form-item>
					</el-col>
				</el-row>

				<el-form-item label="内容/说明" prop="content">
					<el-input type="textarea" v-model="form.content" :rows="3" placeholder="可选" />
				</el-form-item>

				<el-form-item v-if="!isEdit" label="证明材料">
					<el-upload
						v-model:file-list="fileList"
						class="upload-demo"
						drag
						:limit="5"
						:before-upload="beforeUpload"
						:auto-upload="false"
						accept=".jpg,.jpeg,.png,.pdf"
					>
						<el-icon class="el-icon--upload"><UploadFilled /></el-icon>
						<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em>（可选）</div>
						<template #tip>
							<div class="el-upload__tip">支持 JPG/PNG/PDF，单个不超过 20MB，最多 5 个</div>
						</template>
					</el-upload>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="showDialog = false">取消</el-button>
				<el-button type="primary" :loading="submitting" @click="handleSubmit">{{ isEdit ? '保存' : '提交' }}</el-button>
			</template>
		</el-dialog>

		<el-dialog v-model="showView" title="查看社会服务" width="600px">
			<el-descriptions :column="1" border>
				<el-descriptions-item label="类型">{{ currentRow?.serviceType }}</el-descriptions-item>
				<el-descriptions-item label="标题/角色">{{ currentRow?.title }}</el-descriptions-item>
				<el-descriptions-item label="单位">{{ currentRow?.organizationName }}</el-descriptions-item>
				<el-descriptions-item label="级别">{{ currentRow?.level || '-' }}</el-descriptions-item>
				<el-descriptions-item label="起止">{{ currentRow?.startDate }} ~ {{ currentRow?.endDate || '-' }}</el-descriptions-item>
				<el-descriptions-item label="状态">{{ statusText(currentRow?.status) }}</el-descriptions-item>
			</el-descriptions>
			<template #footer>
				<el-button @click="showView = false">关闭</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { Plus, UploadFilled, Download } from '@element-plus/icons-vue'
import { socialServiceApi } from '@/api/academicSocial'
import { ElMessage, ElMessageBox } from 'element-plus'

const showDialog = ref(false)
const isEdit = ref(false)
const showView = ref(false)
const currentRow = ref(null)
const formRef = ref()
const submitting = ref(false)

const form = reactive({
	service_type: '',
	title: '',
	content: '',
	organization_name: '',
	level: '',
	start_date: '',
	end_date: ''
})

const rules = {
	service_type: [{ required: true, message: '请选择类型', trigger: 'change' }],
	title: [{ required: true, message: '请输入标题/角色', trigger: 'blur' }],
	organization_name: [{ required: true, message: '请输入单位名称', trigger: 'blur' }]
}

const fileList = ref([])
const tableData = ref([])

const levelTag = (level) => ({ '校级': 'info', '市级': 'info', '省级': 'warning', '国家级': 'danger', '国际级': 'success' }[level] || 'info')
const statusTag = (s) => ({ 'PENDING': 'warning', 'APPROVED': 'success', 'REJECTED': 'danger' }[s] || 'info')
const statusText = (s) => ({ 'PENDING': '待审核', 'APPROVED': '已通过', 'REJECTED': '已驳回' }[s] || s)

const canEdit = (row) => true

const openCreate = () => {
	isEdit.value = false
	Object.assign(form, { service_type: '', title: '', content: '', organization_name: '', level: '', start_date: '', end_date: '' })
	fileList.value = []
	showDialog.value = true
}

const beforeUpload = (file) => {
	const okType = ['image/jpeg','image/png','application/pdf']
	const ok = okType.includes(file.type) && file.size <= 20 * 1024 * 1024
	if (!ok) ElMessage.error('请上传 JPG/PNG/PDF 且不超过20MB')
	return ok
}

const disableStart = (date) => {
	if (!form.end_date) return false
	return date.getTime() > new Date(form.end_date).getTime()
}
const disableEnd = (date) => {
	if (!form.start_date) return false
	return date.getTime() < new Date(form.start_date).getTime()
}

const loadTable = async () => {
	try {
		const res = await socialServiceApi.listMine()
		const arr = Array.isArray(res?.data) ? res.data : (Array.isArray(res) ? res : [])
		tableData.value = arr.map(r => ({
			...r,
			organizationName: r.organizationName ?? r.organization_name,
			startDate: r.startDate ?? r.start_date,
			endDate: r.endDate ?? r.end_date
		}))
	} catch (e) {
		console.error(e)
	}
}

const handleSubmit = async () => {
	try {
		if (!formRef.value) return
		await formRef.value.validate()
		submitting.value = true
		if (!isEdit.value) {
			const res = await socialServiceApi.create({
				service_type: form.service_type,
				title: form.title,
				content: form.content || null,
				organization_name: form.organization_name,
				level: form.level || null,
				start_date: form.start_date || null,
				end_date: form.end_date || null
			})
			const id = res?.id || res?.data?.id
			if (fileList.value.length > 0 && id) {
				for (const f of fileList.value) {
					await socialServiceApi.uploadAttachment(id, f.raw || f)
				}
			}
			ElMessage.success('提交成功，等待审核')
		} else {
			await socialServiceApi.update(currentRow.value.id, {
				service_type: form.service_type,
				title: form.title,
				content: form.content || null,
				organization_name: form.organization_name,
				level: form.level || null,
				start_date: form.start_date || null,
				end_date: form.end_date || null
			})
			ElMessage.success('保存成功')
		}
		showDialog.value = false
		await loadTable()
	} catch (e) {
		console.error(e)
		ElMessage.error(e?.response?.data?.message || e?.message || '提交失败')
	} finally {
		submitting.value = false
	}
}

const handleView = (row) => { currentRow.value = row; showView.value = true }

const handleEdit = (row) => {
	currentRow.value = row
	isEdit.value = true
	Object.assign(form, {
		service_type: row.serviceType ?? row.service_type,
		title: row.title,
		content: row.content || '',
		organization_name: row.organizationName ?? row.organization_name,
		level: row.level || '',
		start_date: row.startDate || '',
		end_date: row.endDate || ''
	})
	showDialog.value = true
}

const handleDelete = async (row) => {
	try {
		await ElMessageBox.confirm('确定删除该记录吗？', '删除确认', { type: 'warning' })
		await socialServiceApi.remove(row.id)
		ElMessage.success('删除成功')
		await loadTable()
	} catch (e) {
		if (e !== 'cancel') ElMessage.error(e?.response?.data || e?.message || '删除失败')
	}
}

const exportData = async () => {
	const { exportData: exportUtil } = await import('@/utils/exportUtils')
	
	const filters = {}
	
	await exportUtil('volunteer-services', filters, '社会服务列表.xlsx')
}

loadTable()
</script>

<style scoped>
.page {}
.page-header { margin-bottom: 16px; }
.page-title { margin: 0; font-size: 20px; }
.page-subtitle { margin: 4px 0 0 0; color: #666; }
.upload-demo { width: 100%; }
</style> 